package org.puc.enquete.servlet;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.puc.enquete.ejb.EnqueteBeanLocal;
import org.puc.enquete.ejb.VotoBeanLocal;
import org.puc.enquete.entity.Enquete;
import org.puc.enquete.entity.Opcao;

public class MostrarGrafico extends HttpServlet {

    @EJB
    private EnqueteBeanLocal enqueteBean;

    private DefaultPieDataset createDataset(List<Opcao> opcoes) {

        DefaultPieDataset dataset = new DefaultPieDataset();
        for (Opcao opcao : opcoes) {
            dataset.setValue(opcao.getDescricao(), opcao.getQuantidadeVotos().doubleValue());
        }
        return dataset;

    }

    private JFreeChart createChart(DefaultPieDataset  dataset) {

        JFreeChart chart = ChartFactory.createPieChart(
                "Resultados da Enquete",
                dataset,
                true,
                true,
                false
            );

        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setSectionOutlinesVisible(true);
        plot.setNoDataMessage("Nenhum voto...");

        chart.setBackgroundPaint(java.awt.Color.white);

        Color[] colors = {Color.blue, Color.yellow, Color.green};
        PieRenderer renderer = new PieRenderer(MostrarEstatisticas.cores);
        renderer.setColor(plot, dataset);


        return chart;

    }

    public class PieRenderer {
        private Color[] color;

        public PieRenderer(Color[] color)
        {
            this.color = color;
        }

        public void setColor(PiePlot plot, DefaultPieDataset dataset)
        {
            List <Comparable> keys = dataset.getKeys();
            int aInt;

            for (int i = 0; i < keys.size(); i++)
            {
                aInt = i % this.color.length;
                plot.setSectionPaint(keys.get(i), this.color[aInt]);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

         try {

            String idEnquete = request.getParameter("enquete");

            if (idEnquete == null || idEnquete.trim().length() == 0) {

                throw new Exception("Estatística inválida!");

            }

            Enquete enquete = enqueteBean.obterEnquete(Integer.parseInt(idEnquete));

            JFreeChart chart = createChart(createDataset(enquete.getOpcoes()));

            //ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            //ServletUtilities.

            OutputStream os = response.getOutputStream();

            //filename = ServletUtilities.saveChartAsPNG(chart, 500, 300, info, session);
            response.setContentType("image/png");
            ChartUtilities.writeChartAsPNG(os, chart, 600, 350);
            os.flush();
            //pw.flush();
            
        } catch (Throwable e) {

            response.sendError(500, "Erro ao gerar imagem!");

        }
        
    } 

}
